﻿using Lanbt.Core.Entity.Dto;
using Lanbt.Core.Utility;
using Lanbt.Core.Utility.ExceptionExtent;
using Lanbt.Core.Utility.Helper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Lanbt.Core.Web.Filter
{
    public class GlobalExceptionFilter:ExceptionFilterAttribute
    {
        public void OnException(ExceptionContext context)
        {
            if(context.ExceptionHandled == false)
            {
                LogHelper<GlobalExceptionFilter>.Error(context.Exception);
                ResultOutput<string> result = new ResultOutput<string>();
                if(context.Exception is LanbtException)
                {
                    var quartzException = (LanbtException)context.Exception;
                    result.Code = quartzException.Code;
                }
                else
                {
                    result.Code = -1;
                }
                result.ErrorMsg = context.Exception.Message + context.Exception.InnerException?.Message;

                //序列化字段小驼峰配置
                var serializerSetting = new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                };
                
                context.Result = new ContentResult
                {
                    // 返回状态码设置为200，表示成功
                    StatusCode = StatusCodes.Status200OK,
                    // 设置返回格式
                    ContentType = "application/json;charset=utf-8",
                    Content = JsonConvert.SerializeObject(result, serializerSetting)
                };
            }

            base.OnException(context);
        }

        public override Task OnExceptionAsync(ExceptionContext context)
        {
            if (GlobalContext.HostingEnvironment.IsDevelopment())
            {
                OnException(context);
            }
            return Task.CompletedTask;
        }
    }
}
